var express = require('express');
const shortId = require('shortid')
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')

const adapter = new FileSync(__dirname + '/../data/db.json')
const db = low(adapter)

// Set some defaults
db.defaults({
    accounts: [],
  })
  .write()
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});
router.get('/account', (req, res, next) => {
  const accounts = db.get('accounts').value()
  res.render('showAccount', {
    accounts: accounts
  })
})
router.get('/account/create', (req, res, next) => {
  res.render('createAccount')
})
router.post('/account/create', (req, res, next) => {
  console.log(req.body)
  //添加到lowdb中
  db.get('accounts').unshift({
    id: shortId.generate(),
    ...req.body
  }).write()
  res.render('success', {
    message: '添加成功',
    link: '/account'
  })
})
router.get('/account/:id', (req, res, next) => {
  console.log(req.params.id)
  db.get('accounts').remove({
    id: req.params.id
  }).write()
  res.render('success', {
    message: '删除成功',
    link: '/account'
  })
})
module.exports = router;